package com.nanhu.test.slide;

import java.util.List;

import com.nanhu.test.R;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;

public class Chouti extends Activity{
	
	private GridView gv;
	
	private SlidingDrawer sd;
	
	private ImageView iv;
	
	private List<ResolveInfo> apps;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chouti_layout);
		loadApps();
		gv = (GridView)findViewById(R.id.allApps);
		sd = (SlidingDrawer)findViewById(R.id.sliding);
		iv = (ImageView)findViewById(R.id.imageViewIcon);
		gv.setAdapter(new GridAdapter());
		sd.setOnDrawerOpenListener(new OnDrawerOpenListener() {
			
			@Override
			public void onDrawerOpened() {
				iv = (ImageView)findViewById(R.id.imageViewIcon);
			}
		});
		sd.setOnDrawerCloseListener(new OnDrawerCloseListener() {
			
			@Override
			public void onDrawerClosed() {
				iv = (ImageView)findViewById(R.id.imageViewIcon);
			}
		});
	}
	
	private void loadApps(){
		Intent intent = new Intent(Intent.ACTION_MAIN, null);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		apps = getPackageManager().queryIntentActivities(intent, 0);
	}
	
	public class GridAdapter extends BaseAdapter{

		public GridAdapter(){
			
		}
		
		@Override
		public int getCount() {
			return apps.size();
		}

		@Override
		public Object getItem(int position) {
			return apps.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView = null;
			if(convertView == null){
				imageView = new ImageView(Chouti.this);
				imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
				imageView.setLayoutParams(new GridView.LayoutParams(50, 50));
			}else{
				imageView = (ImageView)convertView;
			}
			
			ResolveInfo ri = apps.get(position);
			imageView.setImageDrawable(ri.activityInfo.loadIcon(getPackageManager()));
			return imageView;
		}
		
	}
}
